package com.example.erp.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.example.erp.config.CommonConfig;
import com.example.erp.utils.JwtUtils;
import com.example.erp.utils.Result;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        为true放行,false不放行
        String url = request.getRequestURL().toString();
        if(url.contains("/login")){
            //放行
            return true;
        }
        String jwt = request.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            Result error = Result.login(CommonConfig.resultMsg.TOKENNULL.getDescription());
            String notLogin = JSONObject.toJSONString(error);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }
        try{
            Claims claims = JwtUtils.parseJwt(jwt);
        }catch(Exception e){
            e.printStackTrace();
            Result error = Result.login(CommonConfig.resultMsg.TOKENERROR.getDescription());
            String notLogin = JSONObject.toJSONString(error);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(notLogin);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
